package eu.web.plugin.filter;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.web.security.access.AccessAnalyst;
import eu.web.security.access.AccessIdentity;
import eu.web.security.access.IdentityFetcher;

/**
 * 访问控制过滤器
 * @author 吴振振
 * @version 20110423 fixed
 */
@WebFilter(urlPatterns="/*",
		dispatcherTypes = {
		DispatcherType.REQUEST, 
		DispatcherType.FORWARD, 
	})
public class IdentityFilter implements Filter {
	AccessAnalyst analyst=null;
	
	public void destroy() {

	}

	/**
	 * 过滤方法
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest r = (HttpServletRequest) request;
		AccessIdentity id = IdentityFetcher.fetch(r);
		String url =r.getRequestURI().replace(r.getContextPath(), "");
		if("/".equals(url)){
			chain.doFilter(request, response);
			return;
		}
		if(analyst.check(url, id)){
			chain.doFilter(request, response);
		}
		else{
			if(response instanceof HttpServletResponse)
				((HttpServletResponse)response).sendError(401,"Unauthorized Access");
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		 analyst = AccessAnalyst.getInstance();
	}
}
